package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JSONResult;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class PermissionInterator implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {

        //1.获取当前登录用户
        Employee employee = UserContext.getCurrentUser();
        //2.判断是否超级管理员
        if (employee.isAdmin()){

            //是-->放行
            return true;
        }
            //不是-->到第三步
        //3.获取当前要执行的处理方法(被拦截的方法)
        if (!(handler instanceof HandlerMethod)){  //如果不是HandlerMethod,代表是静态资源,直接放行(*.do的不存在这个问题)

            return true;
        }
            HandlerMethod method = (HandlerMethod) handler;

            RequiredPermission annotation = method.getMethodAnnotation(RequiredPermission.class);
            //4.判断是否贴有自定义注解

            if (annotation==null) {

                //不是-->放行
                return true;
            }
            //是-->到第五步
            //5.获取方法的权限表达式
            String expression = annotation.expression();
            //6.获取当前登录用户拥有的权限表达式集合
            List<String> list = UserContext.getExpression();
            //7.判断用户拥有的权限表达式集合是否包含该方法的权限表达式
            if (list.contains(expression)){

                //包含-->放行
                return true;

        }
        //不包含-->不放行,跳到错误页面
        if (!method.hasMethodAnnotation(ResponseBody.class)){  //判断有没有贴ResponseBody注解

            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request, response);
        }else {

            JSONResult jsonResult = new JSONResult(false, "您没有权限操作");
            response.setContentType("application/jsonResult;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(jsonResult));
        }
        return false;
    }
}
